#include "widget.h"

#include <qgeopositioninfosource.h>
#include <qgeosatelliteinfosource.h>
#include <qnmeapositioninfosource.h>
#include <qgeopositioninfo.h>

QTM_USE_NAMESPACE

Widget::Widget(QWidget *parent):QWidget(parent)
{
    textInput = new QTextEdit("Some text", this);

    button1 = new QPushButton("Press!",this);
    connect(button1, SIGNAL(clicked()), this, SLOT(button1Clicked()));

    lastPos = new QGeoPositionInfo();
    QVBoxLayout* mainLayout = new QVBoxLayout;

    location = QGeoPositionInfoSource::createDefaultSource(this);
    connect(location,SIGNAL(positionUpdated(QGeoPositionInfo)),this,SLOT(positionUpdated(QGeoPositionInfo)));
    location->startUpdates();

    satellites = QGeoSatelliteInfoSource::createDefaultSource(this);

    mainLayout->addWidget(textInput);
    mainLayout->addWidget(button1);

    this->setLayout(mainLayout);
}

Widget::~Widget()
{
    location->stopUpdates();
    if (satellites)
        satellites->stopUpdates();
}

void Widget::positionUpdated(const QGeoPositionInfo &gpsPos)
{
    if (gpsPos.isValid()){
        if (lastPos->coordinate() != gpsPos.coordinate()){
            textInput->insertPlainText("Position is " + QString::number(gpsPos.coordinate().latitude()) + " " + QString::number(gpsPos.coordinate().longitude()) + "\n");
            lastPos->setCoordinate(gpsPos.coordinate());
        }
    }
    else
        textInput->insertPlainText(tr("No satellites in use\n"));
}

void Widget::button1Clicked()
{
    QGeoPositionInfo gpsPos = location->lastKnownPosition();
    textInput->insertPlainText("Your position is " + QString::number(gpsPos.coordinate().latitude()) + " " + QString::number(gpsPos.coordinate().longitude()) + "\n");
}
